const express = require('express')
const router = express.Router()
const ManagerModel = require('../../model/managerModel')
const { md5, getUnix } = require('../../model/tools')

router.get('/', async function (req, res) {
  // 获取管理员数据
  try {
    let result = await ManagerModel.find({}).sort({_id: -1});
    res.render('admin/manager/index', {
      list: result
    })
  } catch (error) {

  }
})

router.get('/add', function (req, res) {
  res.render('admin/manager/add.html')
})

router.post('/doAdd', async function (req, res) {
  // 1. 获取表单提交的数据
  var username = req.body.username
  var password = req.body.password
  var rpassword = req.body.rpassword
  var email = req.body.email
  var phone = req.body.phone 
  var state = req.body.state 
  // 2. 验证数据是否合法
  if(username == '') {
    res.render('admin/public/error', {
      redirectUrl: '/admin/manager/add',
      message: '用户名不能为空'
    })
    return
  }

  if(password.length < 6) {
    res.render('admin/public/error', {
      message: '密码长度不能小于6位',
      redirectUrl: '/admin/manager/add'
    })
    return
  }

  if(password !== rpassword) {
    res.render('admin/public/error', {
      message: '密码和确认密码输入不一致',
      redirectUrl: '/admin/manager/add'
    })
    return
  }

  // 3. 判断数据库里面有没有我们要增加的数据
  let result = await ManagerModel.find({'username': username})

  if(result && result.length > 0) {
    res.render('admin/public/error', {
      message: '当前用户已经存在，请换一个用户',
      redirectUrl: '/admin/manager/add'
    })
  } else {
    // 4. 执行增加操作
    var user = new ManagerModel({
      username, 
      password: md5(password), 
      rpassword, email, phone, state,
      create_time: getUnix()
    })
    user.save((err, data) => {
      if(err) {
        console.log(err)
        res.render('admin/public/error', {
          redirectUrl: '/admin/manager/add',
          message: '失败'
        })
        return;
      }
      res.render('admin/public/success', {
        redirectUrl: '/admin/manager',
        message: '成功'
      })
    });
  }

})

router.get('/delete', function(req, res) {
  var _id = req.query.id
  ManagerModel.deleteOne({_id}, function(err, data) {
    if(err) {
      console.log(err)
      res.send({
        code: 404,
        msg: '失败'
      })
      return;
    }
    if(data && data.deletedCount > 0) {
      res.send({
        code: 200,
        msg: '成功'
      })
    } else {
      res.send({
        code: 404,
        msg: '失败'
      })
    }
  })
})

router.get('/edit', async function (req, res) {
  // 获取管理员数据
  var id = req.query.id
  let result = await ManagerModel.find({'_id': id});
  if(result.length > 0) {
    res.render('admin/manager/edit', {
      list: result[0]
    })
  } else {
    res.redirect('/admin/manager')
  }
})

router.post('/doEdit', async function (req, res) {
  // 1. 获取表单提交的数据
  var _id = req.body.id
  var password = req.body.password
  var rpassword = req.body.rpassword
  var email = req.body.email
  var phone = req.body.phone 
  var state = req.body.state 
  // 2. 验证数据是否合法
  if(password.length > 0) { // 修改密码
    if(password.length < 6) {
      res.render('admin/public/error', {
        message: '密码长度不能小于6位',
        redirectUrl: '/admin/manager/edit?id=' + _id
      })
      return
    }

    if(password !== rpassword) {
      res.render('admin/public/error', {
        message: '密码和确认密码输入不一致',
        redirectUrl: '/admin/manager/edit?id=' + _id
      })
      return
    }  
    let result = await ManagerModel.find({_id})
    if(result && result.length > 0) {
      // 4. 执行修改操作
      var user = await ManagerModel.updateOne({_id}, 
        {password: md5(password), email, phone, state, modifyTime: getUnix()})
      if(user.modifiedCount > 0) {
        res.render('admin/public/success', {
          redirectUrl: '/admin/manager',
          message: '成功'
        })
      } else {
        res.render('admin/public/error', {
          redirectUrl: '/admin/manager/edit?id=' + _id,
          message: '失败'
        })
      }
    } else {
      res.render('admin/public/error', {
        redirectUrl: '/admin/manager/edit?id=' + _id,
        message: '失败'
      })
    }
  } else { // 不修改密码，只修改其他信息
    // 3. 判断数据库里面有没有我们要修改的数据
    let result = await ManagerModel.find({_id})
    console.log(result)
    if(result && result.length > 0) {
      // 4. 执行修改操作
      var user = await ManagerModel.updateOne({_id}, 
        {email, phone, state, modify_time: getUnix()})
      if(user.modifiedCount > 0) {
        res.render('admin/public/success', {
          redirectUrl: '/admin/manager',
          message: '成功'
        })
      } else {
        res.render('admin/public/error', {
          redirectUrl: '/admin/manager/edit?id=' + _id,
          message: '失败'
        })
      }
    } else {
      res.render('admin/public/error', {
        redirectUrl: '/admin/manager/edit?id=' + _id,
        message: '失败'
      })
    }
  }
})

module.exports = router
